package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    //拦截器前
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);//权限不足
            return false;
        }
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

        if (StrUtil.isEmpty(json)) {//登录超时
            response.setStatus(401);//权限不足
            return false;
        }
        //根据json查询对象
        User user = JSON.parseObject(json, User.class);
        UserHolder.setLocal(user);
        //续期操作
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, 7, TimeUnit.DAYS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
